<?php
// -----------------------------------------------------------------------------
// 引入
// -----------------------------------------------------------------------------

include "../config/config.php";
include "../auth.php";
include "../DBManager.php";

// -----------------------------------------------------------------------------
// 数据库相关设置
// -----------------------------------------------------------------------------

$dbPath = "../" . $dbPath;
$db = new DBManager("sqlite:" . $dbPath);

// -----------------------------------------------------------------------------
?>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>分类管理</title>
    <link rel="stylesheet" href="../resources/bootstrap-5.2.0-beta1-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="../resources/bootstrap-icons-1.5.0/bootstrap-icons.css">
    <link rel="stylesheet" href="../global.css">
</head>
<body>

<!-- ----------------------------------------------------------------------- -->

<script src="../resources/bootstrap-5.2.0-beta1-dist/js/bootstrap.min.js"></script>
<script src="../resources/jQuery/jquery-3.5.1.js"></script>
<?php include "../globalNavbar.php"; ?>

<!-- ----------------------------------------------------------------------- -->

<!-- div:container start -->
<div class="mainContainer container container-fluid mb-5">

    <!-- 导航栏 开始 -->
    <div class="mt-3">
        <nav style="--bs-breadcrumb-divider: '>';" aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a class="text-decoration-none" href="<?php echo $homepage; ?>">首页</a></li>
                <li class="breadcrumb-item active">分类管理</li>
            </ol>
        </nav>
    </div>
    <!-- 导航栏 结束 -->

    <div class="mt-2">
        <div class="card">
            <div class="card-header">
                <span>
                    <span type="button" class="badge text-bg-dark mx-1 my-1 btnCreateCategory">新建分类<span style="font-size: 0.75em">(alt 1)</span></span>
                    <span type="button" class="badge text-bg-dark mx-1 my-1 btnCreateCategoryInQuantity">批量新建分类<span style="font-size: 0.75em">(alt 2)</span></span>
                </span>
            </div>
        </div>
    </div>

    <!--分类列表 开始-->
    <div id="list" class="mt-2 mb-2">
    </div>
    <!--分类列表 结束-->

</div>
<!-- div:container end -->

<!-- ----------------------------------------------------------------------- -->
<!--以下是 Modal-->
<!-- ----------------------------------------------------------------------- -->

<!-- Modal 创建 category 开始 -->
<div class="modal fade" id="modalCreateCategory" data-bs-backdrop="true" data-bs-keyboard="true" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">新建分类</h1>
                <button type="button" id="btnCloseModalCreateCategory" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">

                <form id="formCreateCategory" action="createCategoryFormAction.php" method="post" class="mb-0">

                    <fieldset class="mt-0">

                        <div class="mt-0">

                            <input type="text"
                                   id="inputCategoryTitle"
                                   name="categoryTitle"
                                   required
                                   autofocus
                                   autocomplete="off"
                                   placeholder="请输入标题"
                                   class="form-control">

                            <!--隐藏的输入框，记录目标 sortNumber，上方新建，下方新建时要用到 -->
                            <input type="text"
                                   id="inputTargetSortNumber"
                                   name="targetSortNumber"
                                   style="display: none">

                        </div>

                        <div class="mt-2">
                            <textarea name="categoryDescription"
                                      id="inputCategoryDescription"
                                      cols="30"
                                      rows="10"
                                      placeholder="请输入描述。按 Ctrl + s 保存。"
                                      class="form-control"></textarea>
                        </div>

                    </fieldset>

                    <fieldset class="mt-2">
                        <button id="btnConfirmCreateCategory" type="button" class="btn btn-outline-primary">保存</button>
                        <button id="btnClearFormCreateCategory" type="button" class="btn btn-outline-secondary">清空</button>
                    </fieldset>

                </form>

            </div>

        </div>
    </div>
</div>
<!-- Modal 创建 category 结束 -->

<!-- ----------------------------------------------------------------------- -->

<!-- Modal 编辑 category 开始 -->
<div class="modal fade" id="modalEditCategory" data-bs-backdrop="true" data-bs-keyboard="true" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">编辑分类</h1>
                <button type="button" id="btnCloseModalEditCategory" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">

                <form id="formEditCategory" action="editCategoryFormAction.php" method="post" class="mb-0">

                    <fieldset class="mt-0">

                        <div class="mt-0">

                            <input id="inputCategoryId"
                                   name="categoryId"
                                   type="text"
                                   placeholder="隐藏的输入框，存入 category ID"
                                   style="display: none">

                            <input type="text"
                                   id="editCategoryTitle"
                                   name="categoryTitle"
                                   required
                                   autofocus
                                   autocomplete="off"
                                   placeholder="请输入标题"
                                   class="form-control">

                        </div>

                        <div class="mt-2">
                            <textarea name="categoryDescription"
                                      id="editCategoryDescription"
                                      cols="30"
                                      rows="10"
                                      placeholder="请输入描述。按 Ctrl + s 保存。"
                                      class="form-control"></textarea>
                        </div>

                    </fieldset>

                    <fieldset class="mt-3">
                        <button id="btnConfirmEditCategory" type="button" class="btn btn-outline-primary">保存</button>
                        <button id="btnClearFormEditCategory" type="button" class="btn btn-outline-secondary">清空</button>
                    </fieldset>

                </form>

            </div>

        </div>
    </div>
</div>
<!-- Modal 编辑 category 结束 -->

<!-- ----------------------------------------------------------------------- -->

<!--Modal 管理 category 开始-->
<div class="modal fade" id="modalManageCategory" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">要执行哪项操作呢？当前分类：<span id="titleOfCategoryToManage" class="text-info text-break"></span></h1>
                <button id="btnCloseModalManageCategory" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">

                <div class="list-group">
                    <button id="btnEditCategory" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-pencil-square"></i></span>
                        编辑
                    </button>
                    <button id="btnDeleteCategory" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-trash"></i></span>
                        删除
                    </button>
                </div>

                <div class="list-group mt-1">
                    <button id="btnCreateCategoryAbove" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-journal-arrow-up"></i></span>
                        上方新建分类
                    </button>
                    <button id="btnCreateCategoryBelow" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-journal-arrow-down"></i></span>
                        下方新建分类
                    </button>
                </div>

               <div class="list-group mt-1">
                   <button id="btnMoveCategoryTopOf" class="list-group-item list-group-item-action">
                       <span class="icon"><i class="bi bi-arrow-bar-up"></i></span>
                       移动到指定分类的上方
                   </button>
                   <button id="btnMoveCategoryUnder" class="list-group-item list-group-item-action">
                       <span class="icon"><i class="bi bi-arrow-bar-down"></i></span>
                       移动到指定分类的下方
                   </button>
                    <button id="btnMoveUpCategory" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-arrow-up"></i></span>
                        上移
                    </button>
                    <button id="btnMoveDownCategory" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-arrow-down"></i></span>
                        下移
                    </button>
               </div>

            </div>

        </div>
    </div>
</div>
<!--Modal 管理 category 结束-->

<!-- ----------------------------------------------------------------------- -->

<!-- Modal 确认删除 category 开始 -->
<div class="modal fade" id="modalConfirmDeleteCategory" data-bs-backdrop="true" data-bs-keyboard="true" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">提示</h1>
                <button type="button" id="btnCloseModalConfirmDeleteCategory" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <p>确定要删除吗？当前分类：<span id="titleOfCategoryToDelete" class="text-info text-break"></span></p>
                <p class="mb-0">当前分类下所有的网址都将被删除，且<span class="text-danger">无法撤消</span>，请谨慎选择。</p>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                <button id="btnConfirmDeleteCategory" type="button" class="btn btn-outline-primary">确定</button>
            </div>

        </div>
    </div>
</div>
<!-- Modal 确认删除 category 结束 -->

<!-- ----------------------------------------------------------------------- -->

<!-- Modal 选择要移动哪个分类的上方 开始 -->
<div class="modal fade" id="modalSelectTargetCategory" data-bs-backdrop="true" data-bs-keyboard="true" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="titleSelectTargetCategory"></h1>
                <button type="button" id="btnCloseModalSelectTargetCategory" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body" id="listOfTargetCategories">
            </div>

        </div>
    </div>
</div>
<!-- Modal 选择要移动哪个分类的上方 结束 -->

<!-- ----------------------------------------------------------------------- -->

<!--Toast 消息弹窗 开始-->
<div aria-live="polite" aria-atomic="true" class="position-relative">
    <div class="toast-container position-fixed top-0 start-50 translate-middle-x">

        <div id="toastShowMessage" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div id="toastHeader" class="toast-header bg-info">
                <strong class="me-auto">提示</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body bg-white">
                <p id="msgContent">需要显示的信息。</p>
            </div>
        </div>

    </div>
</div>
<!--Toast 消息弹窗 结束-->

<!-- ----------------------------------------------------------------------- -->
<!--以下是 JavaScript-->
<!-- ----------------------------------------------------------------------- -->

<!--全局变量-->
<script>
    let titleOfCategoryToManage = "";

    let idOfCategoryToManage = "";
    let idOfPreCategory = "";
    let idOfNextCategory = "";

    let sortNumberOfCategoryToManage = "";
    let sortNumberOfPreCategory = "";
    let sortNumberOfNextCategory = "";

    let createCategoryInQuantity = false;

    let moveAction = "";
</script>

<!-- ----------------------------------------------------------------------- -->

<!--函数定义-->
<script>
    // 通过 ajax 生成分类列表
    function getLists() {
        var url = "listOfCategoryGenerator.php";
        $.get(url)
            .done(function(data ) {
                $("#list").html(data)
            })
            .fail(function () {
                alert("获取列表失败。")
            });
    }
</script>

<!-- ----------------------------------------------------------------------- -->

<!--网页加载时自动执行-->
<script>
    $(function () {
        getLists(); // 网页加载时，自动生成分类列表
    })
</script>

<!-- ----------------------------------------------------------------------- -->

<!--事件处理-->
<script>
    // 点击 分类右侧的「管理」按钮 时执行
    $(document).on("click", ".btnManageCategory", function(e) {

        e.preventDefault()

        titleOfCategoryToManage = $(this).data("title")

        idOfCategoryToManage = $(this).data("id")
        idOfPreCategory = $(this).parent().parent().prev().children().last().children().last().data("id")
        idOfNextCategory = $(this).parent().parent().next().children().last().children().last().data("id")

        sortNumberOfCategoryToManage = $(this).data("sortnumber")
        sortNumberOfPreCategory = $(this).parent().parent().prev().children().last().children().last().data("sortnumber")
        sortNumberOfNextCategory = $(this).parent().parent().next().children().last().children().last().data("sortnumber")

        $("#titleOfCategoryToManage").html(titleOfCategoryToManage)

        /* 启用或禁用上下移动按钮 */

        if (sortNumberOfPreCategory == undefined) {
            $("#btnMoveUpCategory").attr("disabled", "disabled")
        } else {
            $("#btnMoveUpCategory").removeAttr("disabled")
        }

        if (sortNumberOfNextCategory == undefined) {
            $("#btnMoveDownCategory").attr("disabled", "disabled")
        } else {
            $("#btnMoveDownCategory").removeAttr("disabled")
        }

        /* 显示 Modal */
        const myModal = new bootstrap.Modal($("#modalManageCategory"), {
            backdrop: true,
            keyboard: true
        })
        myModal.show()

    })
</script>

<!-- ----------------------------------------------------------------------- -->

<!--上方新建，下方新建-->
<script>
    // 上方新建
    $("#btnCreateCategoryAbove").on("click", function () {
        $("#inputTargetSortNumber").val(sortNumberOfCategoryToManage)
        const myModal = new bootstrap.Modal($("#modalCreateCategory"), {
            backdrop: "static",
            keyboard: true
        })
        myModal.show()

        $("#btnCloseModalManageCategory").click()
    })

    // 下方新建
    $("#btnCreateCategoryBelow").on("click", function () {
        $("#inputTargetSortNumber").val(sortNumberOfNextCategory)
        const myModal = new bootstrap.Modal($("#modalCreateCategory"), {
            backdrop: "static",
            keyboard: true
        })
        myModal.show()

        $("#btnCloseModalManageCategory").click()
    })
</script>

<!-- ----------------------------------------------------------------------- -->

<!--新建分类-->
<script>

    // 点击「新建分类」按钮时，弹出相应 modal
    $(".btnCreateCategory").on("click", function () {

        // 稳妥起见，清空相应的记录
        $("#inputTargetSortNumber").val("")

        const myModal = new bootstrap.Modal($("#modalCreateCategory"), {
            backdrop: "static",
            keyboard: true
        })
        myModal.show()

    })

    // 点击「批量新建分类」按钮时，弹出相应 modal
    $(".btnCreateCategoryInQuantity").on("click", function () {
        createCategoryInQuantity = true
        $(".btnCreateCategory").click()
    })

    // modal 弹出时，自动聚焦 title 输入框
    $('#modalCreateCategory').on('shown.bs.modal', function () {
        $('#inputCategoryTitle').focus();
    });

    // 点击 新建分类 modal 中的「确认」按钮 时执行
    $("#btnConfirmCreateCategory").on("click", function (e) {

        const categoryTitle = $("#inputCategoryTitle").val()

        if (categoryTitle.trim() == "") {

            alert("请输入分类标题！")
            $("#inputCategoryTitle").val("") // 清空空格
            $("#inputCategoryTitle").focus()

        } else {

            const url = "createCategoryFormAction.php";

            $.post(url, $("#formCreateCategory").serialize())
                .done(function (data) {

                    // 清空输入框
                    $("#inputCategoryTitle").val("")
                    $("#inputCategoryDescription").val("")

                    if (createCategoryInQuantity) {
                        $("#inputCategoryTitle").focus()
                    } else {
                        $("#btnCloseModalCreateCategory").click()
                    }

                    $("#msgContent").text(data)
                    $("#toastHeader").attr("class", "toast-header bg-info")
                    const toast = new bootstrap.Toast(toastShowMessage, {"delay": 1500})
                    toast.show()

                })
                .fail(function () {
                    alert("保存失败！")
                })

        }

    })

    // modal 关闭时，取消批量新建分类，并刷新分类列表
    $('#modalCreateCategory').on('hidden.bs.modal', function () {
        createCategoryInQuantity = false

        // 清空未保存的数据
        $("#inputCategoryTitle").val("")
        $("#inputCategoryDescription").val("")

        // 清除「上方新建分类」「下方新建分类」时留下的数据
        // 使得下次正常「新建分类」时，不会受到影响
        $("#inputTargetSortNumber").val("")

        getLists()
    });

    // 执行 when 点击 the button 清空 in the modal to 新建分类
    $("#btnClearFormCreateCategory").on("click", function (e) {
        $("#inputCategoryTitle").val("")
        $("#inputCategoryDescription").val("")
        $("#inputCategoryTitle").focus()
    })

    // 按下 ctrl + s 时保存。
    // 参考资料：https://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery
    $("#inputCategoryTitle, #inputCategoryDescription").bind('keydown', function(event) {
        if (event.ctrlKey || event.metaKey) {
            switch ((event.key).toLowerCase()) {
                case 's':
                    event.preventDefault();
                    $("#btnConfirmCreateCategory").click();
            }
        }
    });

</script>

<!----------------------------------------------------------------------------->

<!--删除分类-->
<script>
    // 点击 管理面板中的「删除」按钮 时执行
    $("#btnDeleteCategory").on("click", function () {
        // 关闭 管理 modal
        $("#btnCloseModalManageCategory").click()

        $("#titleOfCategoryToDelete").html(titleOfCategoryToManage)

        /* 显示 确认删除 Modal */
        const myModal = new bootstrap.Modal($("#modalConfirmDeleteCategory"), {
            backdrop: true,
            keyboard: true
        })
        myModal.show()
    })

    // 点击 删除确认弹窗中的「确认」按钮 时执行
    $("#btnConfirmDeleteCategory").on("click", function () {

        // 关闭 删除确认 modal
        $("#btnCloseModalConfirmDeleteCategory").click()

        // 执行删除
        let url = `delete.php?id=${idOfCategoryToManage}`
        $.get(url)
            .done(function(data ) {
                getLists()
            })
            .fail(function () {
                alert("删除失败。")
            });

    })
</script>

<!----------------------------------------------------------------------------->

<!--移动到指定分类的上方或下方-->
<script>

    function openListOfTargetCategory() {
        const url = `listOfTargetCategoriesGenerator.php`
        $.get(url)
            .done(function(data) {

                // 关闭 modal
                $("#btnCloseModalManageCategory").click()

                $("#listOfTargetCategories").html(data)

                const myModal = new bootstrap.Modal($("#modalSelectTargetCategory"), {
                    backdrop: true,
                    keyboard: true
                })
                myModal.show()

            })
            .fail(function () {
                alert("请求列表失败！")
            });
    }

    $("#btnMoveCategoryTopOf").on("click", function (e) {
        moveAction = "top";
        $("#titleSelectTargetCategory").html("希望移动到哪个分类的<span class='text-info'>上方</span>呢？")
        openListOfTargetCategory()
    })

    $("#btnMoveCategoryUnder").on("click", function (e) {
        moveAction = "under";
        $("#titleSelectTargetCategory").html("希望移动到哪个分类的<span class='text-info'>下方</span>呢？")
        openListOfTargetCategory()
    })

    $(document).on("click", ".selectAsTarget", function(e) {

        let sortNumberOfTargetCategory = ""
        let action = ""

        switch (moveAction) {
            case "top":

                sortNumberOfTargetCategory = $(this).data("sortnumber")
                action = "top"

                if ($(this).data("sortnumber") == sortNumberOfCategoryToManage) {
                    $(this).addClass("disabled")
                    $(this).css("color", "red")
                    alert("选中的这个分类，是你当前正想要移动的。请重新选择！")
                    return; // 跳出当前函数
                }

                if ($(this).data("sortnumber") == sortNumberOfNextCategory) {
                    $(this).addClass("disabled")
                    $(this).css("color", "red")
                    alert("移动之后，还是在当前位置，请重新选择！")
                    return;
                }

                break;
            case "under":

                // 顺序排列的列表，移动到最下方一个分区的下方时，这里获取到的值是 undefined。
                sortNumberOfTargetCategory = $(this).next().data("sortnumber")
                action = "under"

                if ($(this).data("sortnumber") == sortNumberOfCategoryToManage) {
                    $(this).addClass("disabled")
                    $(this).css("color", "red")
                    alert("选中的这个分类，是你当前正想要移动的。请重新选择！")
                    return; // 跳出当前函数
                }

                if ($(this).data("sortnumber") == sortNumberOfPreCategory) {
                    $(this).addClass("disabled")
                    $(this).css("color", "red")
                    alert("移动之后，还是在当前位置，请重新选择！")
                    return; // 跳出当前函数
                }

        }

        const url = `changeSortNumberOfCategoryFromAToB.php?source=${sortNumberOfCategoryToManage}&target=${sortNumberOfTargetCategory}&action=${action}`

        $.get(url)
            .done(function(data) {

                // 关闭 modal
                $("#btnCloseModalSelectTargetCategory").click()
                getLists()

            })
            .fail(function () {
                alert("移动失败！")
            });

    })

</script>

<!----------------------------------------------------------------------------->

<!--上下移动分类-->
<script>
    // 上移
    $("#btnMoveUpCategory").on("click", function (e) {

        // 关闭 管理 modal
        $("#btnCloseModalManageCategory").click();

        let idOne = idOfCategoryToManage;
        let sortNumberOne = sortNumberOfCategoryToManage;

        let idTwo = idOfPreCategory;
        let sortNumberTwo = sortNumberOfPreCategory;

        if (idTwo !== undefined) {

            let url = `changeSortNumberOfCategory.php?idOne=${idOne}&idTwo=${idTwo}&sortNumberOne=${sortNumberOne}&sortNumberTwo=${sortNumberTwo}`;

            $.get(url)
                .done(function(data ) {
                    getLists()
                })
                .fail(function () {
                    alert("请求列表失败。")
                });

        }

    })

    // 下移
    $("#btnMoveDownCategory").on("click", function (e) {

        // 关闭 管理 modal
        $("#btnCloseModalManageCategory").click();

        let idOne = idOfCategoryToManage;
        let sortNumberOne = sortNumberOfCategoryToManage;

        let idTwo = idOfNextCategory;
        let sortNumberTwo = sortNumberOfNextCategory;

        if (idTwo !== undefined) {

            let url = `changeSortNumberOfCategory.php?idOne=${idOne}&idTwo=${idTwo}&sortNumberOne=${sortNumberOne}&sortNumberTwo=${sortNumberTwo}`;

            $.get(url)
                .done(function(data ) {
                    getLists()
                })
                .fail(function () {
                    alert("请求列表失败。")
                });

        }

    })
</script>

<!----------------------------------------------------------------------------->

<!--编辑分类-->
<script>
    // 点击 管理弹窗中的「编辑」按钮 时执行
    $("#btnEditCategory").on("click", function () {

        // 关闭 管理 modal
        $("#btnCloseModalManageCategory").click()

        // 请求分类信息
        let url = `editCategory.php?id=${idOfCategoryToManage}`

        $.get(url)
            .done(function(data ) {

                // 初始化 编辑分类 modal
                let jsonObj =JSON.parse(data)
                $("#inputCategoryId").val(idOfCategoryToManage)
                $("#editCategoryTitle").val(jsonObj.title)
                $("#editCategoryDescription").val(jsonObj.description)

                // 弹出 编辑分类 modal
                const myModal = new bootstrap.Modal($("#modalEditCategory"), {
                    backdrop: "static",
                    keyboard: true
                })
                myModal.show()

            })
            .fail(function () {
                alert("获取分类详情失败。")
            });

    })

    // modal 弹出时，自动聚焦 title 输入框
    $('#modalEditCategory').on('shown.bs.modal', function () {
        $('#editCategoryTitle').focus();
    });

    // 点击 分类编辑 modal 中的「保存」按钮 时执行
    $("#btnConfirmEditCategory").on("click", function () {

        // 取得输入的分类标题
        const categoryTitle =$("#editCategoryTitle").val()

        // 判断分类标题是否为空
        if (categoryTitle.trim() == "") {
            // 标题为空
            alert("请输入分类标题。")
            $("#editCategoryTitle").val("")
            $("#editCategoryTitle").focus()
        } else {
            // 标题不为空

            const url = "editCategoryFormAction.php"

            $.post(url, $("#formEditCategory").serialize())
                .done(function (data) {

                    // 关闭 分类编辑 modal
                    $("#btnCloseModalEditCategory").click()

                    getLists()

                    $("#msgContent").text(data)
                    $("#toastHeader").attr("class", "toast-header bg-info")
                    const toast = new bootstrap.Toast(toastShowMessage, {"delay": 1500})
                    toast.show()

                })
                .fail(function () {
                    alert("保存失败！")
                })

        }

    })

    // 点击 分类编辑 modal 中的「清空」按钮 时执行
    $("#btnClearFormEditCategory").on("click", function (e) {
        $("#editCategoryTitle").val("")
        $("#editCategoryDescription").val("")
        $("#editCategoryTitle").focus()
    })

    // 按下 ctrl + s 时保存。
    // 参考资料：https://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery
    $("#editCategoryTitle, #editCategoryDescription").bind('keydown', function(event) {
        if (event.ctrlKey || event.metaKey) {
            switch ((event.key).toLowerCase()) {
                case 's':
                    event.preventDefault();
                    $("#btnConfirmEditCategory").click();
            }
        }
    });
</script>

<!----------------------------------------------------------------------------->

<!--快捷键-->
<script>

    $(document).keydown(function(event){
        // 查看更多 keycode，参考：https://www.toptal.com/developers/keycode
        if (event.altKey) {
            switch (event.key) {
                case "1":
                    // 点击「新建分类」按钮
                    event.preventDefault();
                    $(".btnCreateCategory").click();
                    break;
                case "2":
                    // 点击「批量新建分类」按钮
                    event.preventDefault();
                    $(".btnCreateCategoryInQuantity").click();
                    break;
            }
        }
    })

</script>

<!----------------------------------------------------------------------------->

<!-- 添加「返回顶部按钮」 -->
<script src="../resources/vanilla-back-to-top/index.js"></script>
<script src="../resources/vanilla-back-to-top/config.js"></script>

<!----------------------------------------------------------------------------->

</body>
</html>
